package com.health.scheduling.service.impl;

import java.time.Duration;
import java.util.List;

import com.health.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.health.scheduling.mapper.MedicalAppointmentScheduleMapper;
import com.health.scheduling.domain.MedicalAppointmentSchedule;
import com.health.scheduling.service.IMedicalAppointmentScheduleService;

/**
 * 排班Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-30
 */
@Service
public class MedicalAppointmentScheduleServiceImpl implements IMedicalAppointmentScheduleService
{
    @Autowired
    private MedicalAppointmentScheduleMapper medicalAppointmentScheduleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询排班
     *
     * @param scheduleId 排班主键
     * @return 排班
     */
    @Override
    public MedicalAppointmentSchedule selectMedicalAppointmentScheduleByScheduleId(Long scheduleId)
    {
        String key = "schedule:detail:" + scheduleId;
        // 尝试从缓存获取
        MedicalAppointmentSchedule cached = (MedicalAppointmentSchedule) redisTemplate.opsForValue().get(key);
        if (cached != null) {
            System.out.println("从缓存中获取排班详情：" + scheduleId);
            return cached;
        }
        // 缓存未命中，查询数据库
        MedicalAppointmentSchedule result = medicalAppointmentScheduleMapper.selectMedicalAppointmentScheduleByScheduleId(scheduleId);
        // 存入缓存，设置过期时间（30分钟）
        if (result != null) {
            redisTemplate.opsForValue().set(key, result, Duration.ofMinutes(10));
            System.out.println("已缓存排班详情：" + scheduleId);
        }
        return result;
    }

    /**
     * 查询排班列表
     *
     * @param medicalAppointmentSchedule 排班
     * @return 排班
     */
    @Override

    public List<MedicalAppointmentSchedule> selectMedicalAppointmentScheduleList(MedicalAppointmentSchedule medicalAppointmentSchedule)
    {
        // 生成缓存键
        String key = generateScheduleListCacheKey(medicalAppointmentSchedule);

        // 尝试从缓存获取
        List<MedicalAppointmentSchedule> cached = (List<MedicalAppointmentSchedule>) redisTemplate.opsForValue().get(key);
        if (cached != null) {
            System.out.println("从缓存中获取排班列表：" + medicalAppointmentSchedule);
            return cached;
        }
        // 缓存未命中，查询数据库
        List<MedicalAppointmentSchedule> result = medicalAppointmentScheduleMapper.selectMedicalAppointmentScheduleList(medicalAppointmentSchedule);
        // 存入缓存，设置过期时间（10分钟）
        if (result != null && !result.isEmpty()) {
            redisTemplate.opsForValue().set(key, result, Duration.ofMinutes(10));
            System.out.println("已缓存排班列表：" + medicalAppointmentSchedule);
        }
        return result;
    }

    /**
     * 生成排班列表缓存键
     */
    private String generateScheduleListCacheKey(MedicalAppointmentSchedule schedule) {
        StringBuilder keyBuilder = new StringBuilder("schedule:list:");
        if (schedule == null) {
            return keyBuilder.toString();
        }
        return keyBuilder.toString();
    }

    /**
     * 新增排班
     *
     * @param medicalAppointmentSchedule 排班
     * @return 结果
     */
    @Override
    public int insertMedicalAppointmentSchedule(MedicalAppointmentSchedule medicalAppointmentSchedule)
    {
        medicalAppointmentSchedule.setCreateTime(DateUtils.getNowDate());
        int result = medicalAppointmentScheduleMapper.insertMedicalAppointmentSchedule(medicalAppointmentSchedule);
        // 新增数据后，清除相关的列表缓存
        clearScheduleListCache();
        System.out.println("已缓存新增排班：" + medicalAppointmentSchedule);
        return result;
    }

    /**
     * 修改排班
     *
     * @param medicalAppointmentSchedule 排班
     * @return 结果
     */
    @Override
    public int updateMedicalAppointmentSchedule(MedicalAppointmentSchedule medicalAppointmentSchedule)
    {
        medicalAppointmentSchedule.setUpdateTime(DateUtils.getNowDate());
        int result = medicalAppointmentScheduleMapper.updateMedicalAppointmentSchedule(medicalAppointmentSchedule);
        // 修改数据后，清除相关的缓存
        clearScheduleCache(medicalAppointmentSchedule.getScheduleId());
        clearScheduleListCache();
        return result;
    }

    /**
     * 批量删除排班
     *
     * @param scheduleIds 需要删除的排班主键
     * @return 结果
     */
    @Override
    public int deleteMedicalAppointmentScheduleByScheduleIds(Long[] scheduleIds)
    {
        int result = medicalAppointmentScheduleMapper.deleteMedicalAppointmentScheduleByScheduleIds(scheduleIds);
        // 删除数据后，清除相关的缓存
        for (Long scheduleId : scheduleIds) {
            clearScheduleCache(scheduleId);
        }
        clearScheduleListCache();
        return result;
    }

    /**
     * 删除排班信息
     *
     * @param scheduleId 排班主键
     * @return 结果
     */
    @Override
    public int deleteMedicalAppointmentScheduleByScheduleId(Long scheduleId)
    {
        int result = medicalAppointmentScheduleMapper.deleteMedicalAppointmentScheduleByScheduleId(scheduleId);
        // 删除数据后，清除相关的缓存
        clearScheduleCache(scheduleId);
        clearScheduleListCache();
        return result;
    }

    /**
     * 清除排班详情缓存
     */
    private void clearScheduleCache(Long scheduleId) {
        String detailKey = "schedule:detail:" + scheduleId;
        redisTemplate.delete(detailKey);
    }

    /**
     * 清除排班列表缓存（模糊删除所有以 schedule:list: 开头的键）
     */
    private void clearScheduleListCache() {
        try {
            // 获取所有以 schedule:list: 开头的键
            String pattern = "schedule:list:*";
            redisTemplate.delete(redisTemplate.keys(pattern));
        } catch (Exception e) {
            // 清除缓存失败不影响主要业务逻辑
            System.err.println("清除排班列表缓存失败: " + e.getMessage());
        }
    }
}